import { CLEAR_USER, SET_TOKEN, SET_USER } from '@/actions/user/types.js';
import TokenUtil from '@/utils/token.js';

const stateInit = {
  token: '',
  user: {}
};

function userReducer(state = stateInit, action) {
  if (action.type === SET_TOKEN) {
    TokenUtil.setToken(action.payload);
    return {
      ...state,
      token: action.payload
    };
  }
  if (action.type === SET_USER) {
    return {
      ...state,
      user: action.payload
    };
  }
  if (action.type === CLEAR_USER) {
    TokenUtil.removeToken();
    return {
      ...state,
      token: '',
      user: {}
    };
  }
  return state;
}

export default userReducer;
